﻿@inject IHttpService _httpService
@inject IPopupService PopupService


@if (Id != 0)
{
    <MBorder Color="primary" Style="border-radius:0;height:50%;margin: auto 0;">
        <MCardTitle>应用凭证</MCardTitle>
        <MCardSubtitle>应用凭证</MCardSubtitle>
    </MBorder>

    <div Class="secret-info">
        <strong>Client ID</strong>
        <PCopyableText Text="@ClientId">
            @ClientId
        </PCopyableText>
    </div>
    @if (string.IsNullOrWhiteSpace(Secret))
    {
        <div Class="secret-info">
            <strong>Client Secret（重置后显示）</strong>
            <div>
                XXXXX-XXXXX-XXXXXX-XXXXXX
            </div>
        </div>
    }
    else
    {
        <div Class="secret-info">
            <strong>Client Secret（仅显示一次）</strong>
            <PCopyableText Text="@Secret">
                @Secret
            </PCopyableText>
        </div>
    }


    <MButton Color="primary" Class="mt-4"
             Dark
             OnClick="Reset">
        <MIcon Left>mdi-refresh</MIcon>
        重置
    </MButton>
}

@code {
    [Parameter]
    public int Id { get; set; }
    [Parameter]
    public string ClientId { get; set; }

    string Secret;

    private string _baseUrl = "api/clients/";
    private string _name = "客户端凭据";


    [CascadingParameter]
    public ErrorHandler ErrorHandler { get; set; }

    public async Task Reset()
    {
        try
        {
            var result = await _httpService.PostAsync<ClientSecretResetModel, Result>($"{_baseUrl}secret", new ClientSecretResetModel
            {
                Id = Id
            });
            if (result.Success)
            {
                await PopupService.ToastAsync("重置凭证成功", AlertTypes.Success);

                Secret = result.Message;
                StateHasChanged();
            }
            else
            {
                await PopupService.ToastAsync(result.Message ?? "操作失败", AlertTypes.Error);
            }
        }
        catch (Exception ex)
        {
            await ErrorHandler.ProcessError(ex, $"重置{_name}失败");
        }
    }

}
